import 'package:chewie/chewie.dart';
import 'package:flutter/material.dart';
import 'package:kxy_flutter_app/auth.dart';
import 'package:kxy_flutter_app/components/custom_controls.dart';
import 'package:kxy_flutter_app/components/loading_widget.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:video_player/video_player.dart';

class VideoWidget extends StatefulWidget {
  final double aspectRatio;
  final String url;
  final Function onPlay;

  VideoWidget({
    @required this.url,
    this.aspectRatio = 16 / 9,
    this.onPlay,
  });

  @override
  State<StatefulWidget> createState() {
    return VideoWidgetState();
  }
}

class VideoWidgetState extends State<VideoWidget> {
  ChewieController chewieCtrl;
  VideoPlayerController playerCtrl;

  @override
  void initState() {
    initPlayer();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    var width = MediaQuery.of(context).size.width;
    return Container(
      width: width,
      height: width / widget.aspectRatio,
      child: Builder(
        builder: (cxt) {
          if (chewieCtrl == null) {
            return LoadingWidget();
          }
          return Chewie(controller: chewieCtrl);
        },
      ),
      decoration: BoxDecoration(
        color: Color.fromRGBO(240, 240, 240, 1),
        boxShadow: [
          BoxShadow(
            blurRadius: 1,
            color: Colors.black12,
            offset: Offset(0, 1),
          ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    if (chewieCtrl != null) {
      chewieCtrl.pause().then((value) {
        savePosition().then((value) {
          playerCtrl.dispose();
          chewieCtrl.dispose();
        });
      });
    }

    super.dispose();
  }

  Future initPlayer() async {
    var url = widget.url;
    playerCtrl = VideoPlayerController.network(url);
    chewieCtrl = new ChewieController(
      videoPlayerController: playerCtrl,
      aspectRatio: widget.aspectRatio,
      autoPlay: false,
      looping: false,
      customControls: CustomControls(),
      // showControls: false,
      // materialProgressColors: ChewieProgressColors(
      //   playedColor: Colors.blue,
      //   handleColor: Colors.lightBlue,
      //   backgroundColor: Colors.grey,
      //   bufferedColor: Colors.lightGreen,
      // ),
    );

    playerCtrl.initialize().then((value) async {
      var duration = await getPosition();
      playerCtrl.seekTo(duration);

      setState(() {});

      playerCtrl.play().then((playVal) {
        if (widget.onPlay != null) {
          widget.onPlay();
        }
      });

      playerCtrl.addListener(() {
        if (playerCtrl.value.position == playerCtrl.value.duration) {
          removePosition();
        }
      });
    });
  }

  String get videoId {
    var startIndex = widget.url.lastIndexOf('/');
    var endIndex = widget.url.indexOf('?');
    endIndex = endIndex > 0 ? endIndex : widget.url.length - 1;
    var videoName = widget.url.substring(startIndex + 1, endIndex);
    return videoName + Auth.instance.userId;
  }

  Future<Duration> getPosition() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    if (prefs.containsKey(videoId)) {
      int seconds = prefs.getInt(videoId);
      return new Duration(seconds: seconds);
    }
    return new Duration(seconds: 0);
  }

  Future savePosition() async {
    if (playerCtrl.value.position.inSeconds < playerCtrl.value.duration.inSeconds) {
      SharedPreferences prefs = await SharedPreferences.getInstance();
      int seconds = playerCtrl.value.position.inSeconds;
      await prefs.setInt(videoId, seconds);
    }
  }

  Future removePosition() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.remove(videoId);
  }
}
